<script>
import axios from 'axios';
import http from "@/api/http";

export default {
  name: "ManagerMember",
  data() {
    return {
      parentsCloums: [ //外层table的表头
        {
          name: "项目号",
          id: "1",
          propName: "projectId",
        }, {
          name: "项目名称",
          id: "2",
          propName: "projectName",
        }, {
          name: "项目状态",
          id: "3",
          propName: "projectStatus",
        }
      ],
      tableData: [], //外层table的数据
      sonColumns: [ //内层table的表头
        {
          name: "成员ID",
          id: "1",
          propName: "memberId",
        },
        {
          name: "姓名",
          id: "2",
          propName: "memberName",
        },
        {
          name: "职务",
          id: "3",
          propName: "memberJob",
        }
      ],
      allMembers: [], // 所有成员信息
      newMember: '', // 新增成员信息
    }
  },
  methods: {
    async fetchProjectsAndMembers() {
      try {
        // 获取所有项目的数据
        const projectsResponse = await http.get('/api/members/projects');
        const projects = projectsResponse;

        // 使用 Promise.all 并行获取所有项目的成员信息
        const projectsWithMembers = await Promise.all(projects.map(async (project) => {
          try {
            const membersResponse = await http.get(`/api/members/${project.projectId}/members`);
            const members = membersResponse || [];
            return {
              ...project,
              sonData: members,
              showNewMember: false // 是否显示新增成员输入框
            };
          } catch (error) {
            console.error(`Error fetching members for project ${project.projectId}:`, error);
            return {
              ...project,
              sonData: [],
              showNewMember: false
            };
          }
        }));
        this.tableData = projectsWithMembers;
      } catch (error) {
        console.error('Error fetching projects:', error);
      }
    },
    async fetchAllMembers() {
      try {
        const membersResponse = await http.get('/api/members');
        this.allMembers = membersResponse;
      } catch (error) {
        console.error('Error fetching all members:', error);
      }
    },
    toggleNewMemberInput(project) {
      project.showNewMember = !project.showNewMember;
      this.newMember = '';
    },
    async confirmNewMember(project) {
      if (this.newMember=='') {
        alert("请选择成员");
        return;
      }
      const selectedMember = this.newMember;
      try {
        await http.post('/api/members/add', {
          projectId: project.projectId,
          memberId: selectedMember
        })
        await this.fetchProjectsAndMembers();
        this.newMember = '';
        project.showNewMember = false;
      } catch (error) {
        this.newMember = '';
        console.error('Error adding new member:', error);
      }
    },
    async removeMember(projectId, memberId) {
      try {
        await http.delete(`/api/members/remove`, {
          params: {
            projectId: projectId,
            memberId: memberId
          }
        });
        // 从项目成员列表中移除成员
        const project = this.tableData.find(proj => proj.projectId === projectId);
        project.sonData = project.sonData.filter(member => member.memberId !== memberId);
      } catch (error) {
        console.error('Error removing member:', error);
      }
    },
    cellStyle(){//根据情况显示背景色
      return 'background:#F3F6FF'
    }
  },
  created() {
    this.fetchProjectsAndMembers();
    this.fetchAllMembers();
  }
}
</script>

<template>
  <div class="shopList">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.sonData" style="width: 60%;margin-left:40px" :cell-style="cellStyle">
            <el-table-column
                v-for="(value, id, index) in sonColumns"
                :label="value.name"
                :prop="value.propName"
                :key="index"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                    v-if="scope.row.memberJob !== '项目负责人'"
                    type="danger"
                    @click="removeMember(props.row.projectId, scope.row.memberId)">
                  移出成员
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="props.row.showNewMember" style="margin-left:40px">
            <el-select v-model="newMember" placeholder="选择成员">
              <el-option
                  v-for="member in allMembers"
                  :key="member.memberId"
                  :label="`${member.memberName} - ${member.memberJob}`"
                  :value="member.memberId">
              </el-option>
            </el-select>
            <el-button type="primary" @click="confirmNewMember(props.row)">确认新增</el-button>
          </div>
        </template>
      </el-table-column>
      <!-- 对外层的表格表头进行了遍历循环 -->
      <el-table-column
          v-for="(value, key, index) in parentsCloums"
          :label="value.name"
          :prop="value.propName"
          :key="index"
      >
      </el-table-column>
      <el-table-column
          label="操作"
          fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="primary" v-if="scope.row.projectStatus == '在途'" @click="toggleNewMemberInput(scope.row)">新增成员</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
